#include "persondao.h"
PersonDao *PersonDao::instance = nullptr;

PersonDao *PersonDao::getInstance()
{
    if(instance == nullptr)
    {
        instance = new PersonDao();//不存在则创建
    }
    return instance;//存在就返回实例指针
}

void PersonDao::releaseInstance()
{
    if(instance != nullptr)
    {
    delete  instance;
    instance = nullptr;
    }
}

bool PersonDao::insertPerson(PersonData &person)
{
    QSqlQuery query;
    query.prepare("insert into person (name,start,end,status) values(?,datetime('now','localtime'),datetime('now','localtime'), 0)");
    query.bindValue(0,person.name);
    return query.exec();
}

int PersonDao::getLabel()
{
    QSqlQuery query;
    query.exec("select last_insert_rowid()");
    if(query.next())
    {
        int id = query.record().value(0).toInt();
        return  id;
    }
    return -1;
}

void PersonDao::updateInfo(int id)
{
    QSqlQuery query;
    query.prepare("update person set end = datetime('now','localtime'),status = 1 where id = ? ");
    query.bindValue(0,id);
    query.exec();
}

void PersonDao::selectInfo(vector<PersonData> &v)
{
    QSqlQuery query;
    query.exec("select * from person");
    while(query.next())
    {
        PersonData data;
        data.id = query.record().value("id").toInt();//将查找到的id传给
        data.name = query.record().value("name").toString();
        data.start = query.record().value("start").toDateTime();
        data.end = query.record().value("end").toDateTime();
        data.status = query.record().value("status").toInt();
        v.push_back(data);//最终信息的结果
    }

}

PersonDao::PersonDao()
{
    db = QSqlDatabase::addDatabase("QSQLITE");//加载数据库驱动 使用sqlite数据库
    db.setHostName("facedb");//主机名
    db.setDatabaseName("facedb.db");//数据库名
    db.open();

    QSqlQuery query;
    bool ok = query.exec("create table if not exists person ("
               "id integer primary key autoincrement,"// 自增的主键id
               "name varchar(20),"// 名称，最大长度20字符
               "start datetime," // 开始时间
               "end datetime,"  // 结束时间
               "status integer)");//0:正在考试  1:考试结束
    qDebug()<<"create table is "<< ok;
}

PersonDao::PersonDao(const PersonDao &other)
{

}

PersonDao::~PersonDao()
{

}
